package com.cn.longdistancebusstation.scenic.order;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.callback.OnRecyclerViewItemClickListener;
import com.cn.longdistancebusstation.global.GlobalVariable;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.CancleOrder;
import com.cn.longdistancebusstation.model.Contacter;
import com.cn.longdistancebusstation.model.ListResultIII;
import com.cn.longdistancebusstation.model.ListResultV;
import com.cn.longdistancebusstation.model.Result;
import com.cn.longdistancebusstation.model.ScenicDetails;
import com.cn.longdistancebusstation.model.ScenicOrder;
import com.cn.longdistancebusstation.model.ScenicOrderDetails;
import com.cn.longdistancebusstation.model.ScenicOrderList;
import com.cn.longdistancebusstation.model.SubmitPftOrder;
import com.cn.longdistancebusstation.scenic.ScenicListActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by mucheng on 2018/4/17.
 */

public class PrePayOrderDetails2Activity extends BaseActivity implements OnRecyclerViewItemClickListener,View.OnClickListener {
    private String ticketId,qrcodeIMG,qrcodeURL,remotenum,code,ordernum,orderTime,scenicName,ticketName,ticketAmount,ticketAmountPrice;
    private String touristName,touristCardNo,touristTelephone;
    private Date mLatestPayDate;
    private Timer mTimer;
    private TextView mScenicName,mTicketAmountPrice;
    private TextView mOrderId,mOrderTime;
    private Button mPayOrderBtn,mRefundOrderBtn;
    private ImageView mScheduleNote;
    private int num=1;
    private CancleOrder mCancleOrder;
    private String strUUdone;
    private RecyclerView mRecyclerView;
    private TouristInfoAdapter mTouristInfoAdapter;
    private String touristNum;
    private String scenicImage;
    private TextView mTicketStatusTextView;
    private ScenicOrderDetails mScenicOrderDetails;
    private String status;
    private SubmitPftOrder mSubmitPftOrder;
    private Map<String,String> params;
    private String ticketPrice;
    private BigDecimal ma;
    private BigDecimal mb;
    private BigDecimal mc;
    private BigDecimal mul;
    private BigDecimal mul2;
    private int number=100;
    private ArrayList<Contacter> mContacterList;
    private String str_orderTime;
    private Contacter contacter;
    private String orderId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pre_pay_order_details2);
        getTitleTextView().setText("订单详情");
        //
        mContacterList = new ArrayList<>();
        //
        initView();
        getOrderDetails();
    }

    private void initView() {
        Intent in=getIntent();
        ticketId=in.getStringExtra("orderId");
        status=in.getStringExtra("status");
        mTicketStatusTextView=(TextView)findViewById(R.id.ticket_status);
        if("0".equals(status)){
            mTicketStatusTextView.setText("待付款");
        }else if("1".equals(status)){
            mTicketStatusTextView.setText("待使用");
        }else if("2".equals(status)){
            mTicketStatusTextView.setText("已取消");
        }else if("3".equals(status)){
            mTicketStatusTextView.setText("已使用");
        }else{
            mTicketStatusTextView.setText("已退款");
        }
        mScenicName=(TextView)findViewById(R.id.ticket_name);
        mTicketAmountPrice=(TextView)findViewById(R.id.ticket_amount_price);
        mOrderId=(TextView)findViewById(R.id.ticket_number);
        mOrderTime=(TextView)findViewById(R.id.order_time);
        mPayOrderBtn=(Button)findViewById(R.id.button_pay);
        mPayOrderBtn.setOnClickListener(this);
        mRefundOrderBtn=(Button)findViewById(R.id.button_cancle_order);
        mRefundOrderBtn.setOnClickListener(this);
        mScheduleNote=(ImageView)findViewById(R.id.order_note);
        mScheduleNote.setOnClickListener(this);
        mRecyclerView=(RecyclerView)findViewById(R.id.tourist_list);
        mTouristInfoAdapter=new TouristInfoAdapter();
        mRecyclerView.setAdapter(mTouristInfoAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    }
    private void getOrderDetails() {
        showHud();
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService service=retrofit.create(HttpService.class);
        Call<ListResultV<ScenicOrderDetails>> call=service.getScenicOrderDetails(ticketId);
        call.enqueue(new Callback<ListResultV<ScenicOrderDetails>>() {
            @Override
            public void onResponse(Call<ListResultV<ScenicOrderDetails>> call, Response<ListResultV<ScenicOrderDetails>> response) {
                hideHud();
                ListResultV listResultV=response.body();
                if(listResultV.getHead().getSuccess()) {
                    Gson gson = new Gson();
                    Map<String, String> scenicMap = listResultV.getBody().getData();
                    Type type = new TypeToken<ScenicOrderDetails>() {
                    }.getType();
                    String strScenicOrderJSON = new Gson().toJson(scenicMap);
                    mScenicOrderDetails = gson.fromJson(strScenicOrderJSON, type);
                    if("0".equals(mScenicOrderDetails.getStatus())){
                        mTicketStatusTextView.setText("待付款");
                    }else if("1".equals(mScenicOrderDetails.getStatus())){
                        mTicketStatusTextView.setText("待使用");
                    }else if("2".equals(mScenicOrderDetails.getStatus())){
                        mTicketStatusTextView.setText("已取消");
                    }else if("3".equals(mScenicOrderDetails.getStatus())){
                        mTicketStatusTextView.setText("已使用");
                    }else{
                        mTicketStatusTextView.setText("已退款");
                    }

                    mScenicName.setText(mScenicOrderDetails.getPltitle()+"("+mScenicOrderDetails.getTtitle()+")"+mScenicOrderDetails.getNum()+"张");
                    mTicketAmountPrice.setText(mScenicOrderDetails.getTotalPrice()+"元");
                    mOrderId.setText(mScenicOrderDetails.getOrderId());
                    orderId=mScenicOrderDetails.getOrderId();
                    mOrderTime.setText(mScenicOrderDetails.getCreateTime());
                    touristName=mScenicOrderDetails.getOrdername();
                    touristCardNo=mScenicOrderDetails.getPersonID();
                    touristTelephone=mScenicOrderDetails.getOrdertel();

                    String[] names = touristName.split(",");
                    String[] phones = touristTelephone.split(",");
                    String[] cardNos = touristCardNo.split(",");

                    for(int i=0; i<names.length; i++)
                    {
                        String strName = names[i];
                        String strPhone = phones[i];
                        String strCardNo = cardNos[i];
                        Contacter contacter = new Contacter();

                        contacter.setName(strName);
                        contacter.setTelephone(strPhone);
                        contacter.setCardNo(strCardNo);
                        mContacterList.add(contacter);
                    }
                    mTouristInfoAdapter.notifyDataSetChanged();

                }
            }

            @Override
            public void onFailure(Call<ListResultV<ScenicOrderDetails>> call, Throwable t) {
                hideHud();
                Toast.makeText(PrePayOrderDetails2Activity.this, t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.button_pay:
                payOrder();
                break;
            case R.id.button_cancle_order:
                cancleOrder();
                break;
            case R.id.order_note:
                note();
                break;
        }

    }

    private void note() {
        Intent intent=new Intent(PrePayOrderDetails2Activity.this,ScheduleNoteActivity.class);
        startActivity(intent);
    }

    private void payOrder() {

        Intent in=new Intent(PrePayOrderDetails2Activity.this, TicketOrderPaymentActivity.class);
        in.putExtra("orderNo",mScenicOrderDetails.getPftOrderNum());
        in.putExtra("orderId",mScenicOrderDetails.getPftOrderNum());
        in.putExtra("scenicName",scenicName);
        in.putExtra("ticketName",ticketName);
        in.putExtra("totalAmount",mScenicOrderDetails.getTotalPrice());
        startActivity(in);

//        Intent in=new Intent(PrePayOrderDetails2Activity.this, TicketOrderPaymentActivity.class);
//        in.putExtra("orderNo",mScenicOrderDetails.getOrderId());
//        in.putExtra("sendDate",mScenicOrderDetails.getCreateTime());
//        in.putExtra("totalAmount",mScenicOrderDetails.getTotalPrice());
//        startActivity(in);
    }
    private void cancleOrder() {
        showHud("正在取消订单，请稍后");
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<Result> call=httpService.getCancleOrder(ticketId);
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                hideHud();
                Gson gson=new Gson();
                Result result=response.body();
                if(result!=null){
                    Boolean isSuccess=result.getHead().getSuccess();
                    if(isSuccess){
                        Toast.makeText(PrePayOrderDetails2Activity.this,"取消订单成功",Toast.LENGTH_SHORT).show();
                        Intent in=new Intent(PrePayOrderDetails2Activity.this,CancleOrderDetailsActivity.class);
                        in.putExtra("orderId",orderId);
                        startActivity(in);
                        finish();
                    }else{
                        Toast.makeText(PrePayOrderDetails2Activity.this,"取消订单失败",Toast.LENGTH_SHORT).show();
                    }

                }

            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                hideHud();
                Toast.makeText(PrePayOrderDetails2Activity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    public void onClick(int position) {

    }

    @Override
    public void onClickInnerCtrl(int position) {

    }

    @Override
    public void onClickCoupon(int position) {

    }

    @Override
    public void onClickCheckBox(int position) {

    }

    private class TouristInfoAdapter extends RecyclerView.Adapter<TouristInfoViewHolder>{
        @Override
        public TouristInfoViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(PrePayOrderDetails2Activity.this);
            View view = layoutInflater.inflate(R.layout.tourist_info_recycle_item, parent, false);
            return new TouristInfoViewHolder(view);
        }

        @Override
        public void onBindViewHolder(TouristInfoViewHolder holder, int position) {
            Contacter contacter=mContacterList.get(position);
            holder.bindData(contacter);


        }

        @Override
        public int getItemCount() {
            return mContacterList.size();
        }
    }

    private class TouristInfoViewHolder extends RecyclerView.ViewHolder{
        private TextView mTouristNameTextView;
        private TextView mTouristIdcardNoTextView;
        private TextView mtouristTelephoneTextView;
        public TouristInfoViewHolder(View itemView) {
            super(itemView);
            mTouristNameTextView=(TextView)itemView.findViewById(R.id.tourist_name);
            mTouristIdcardNoTextView=(TextView)itemView.findViewById(R.id.idcard_numbers);
            mtouristTelephoneTextView=(TextView)itemView.findViewById(R.id.telephone_number);
        }

        public void bindData(Contacter contacter) {
            mTouristNameTextView.setText(contacter.getName());
            mTouristIdcardNoTextView.setText(contacter.getCardNo());
            mtouristTelephoneTextView.setText(contacter.getTelephone());
        }
    }
}
